package com.springdatecrm.web.config.shiro;

import com.springdatecrm.web.entity.User;
import com.springdatecrm.web.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /* 授权操作 */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("权限认证-->MyShiroRealm.doGetAuthorizationInfo");

        //授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //设置权限，如果用户没有相应权限，
        //会访问ShiroConfig 过滤器中 shiroFilter 方法配置为授权路径
        //将来这里应该是通过数据库动态授权
        authorizationInfo.addStringPermission("用户管理");
        authorizationInfo.addStringPermission("角色管理");

        return authorizationInfo;
    }


    //主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("身份认证：MyShiroRealm.doGetAuthenticationInfo");

        //获取用户输入的账号
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;

        String usrName = token.getUsername();
        String usrPassword = new String(token.getPassword());
        System.out.println("usrName：" + usrName);
        System.out.println("usrPassword：" + usrPassword);

        //通过username从数据库中查找User对象，如果找到，没找到
        //实际情况中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        User user = userService.getUserByUserName(usrName);
        System.out.println("------>>user=" + user);

        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        } else if (!user.getUsrPassword().equals(usrPassword)) {
            throw new IncorrectCredentialsException("密码不正确");
        }

        //认证信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,   //用户
                user.getUsrPassword(),  //密码
                getName()       //realm name
        );

        return authenticationInfo;
    }
}
